package leetcode_top;
import java.util.*;

import org.junit.Test;

public class Ex350 {
    class Solution {
        public int[] intersect1(int[] nums1, int[] nums2) {
            Map<Integer, Integer> map1 = new HashMap<>();
            Map<Integer, Integer> map2 = new HashMap<>();
            for (int i = 0; i < nums2.length; i++) {
                map2.put(nums2[i], map2.getOrDefault(nums2[i], 0) + 1);
            }
            for (int i = 0; i < nums1.length; i++) {
                map1.put(nums1[i], map1.getOrDefault(nums1[i], 0) + 1);
            }

            List<Integer> list = new ArrayList<>();
            for (int k: map1.keySet()) {
                if (map2.containsKey(k)) {
                    int times = Math.min(map1.get(k), map2.get(k));
                    for (int i = 0; i < times; i++) {
                        list.add(k);
                    }
                }
            }
            return list.stream().mapToInt(Integer::valueOf).toArray();
        }

        public int[] intersect(int[] nums1, int[] nums2) {
            Map<Integer, Integer> map = new HashMap<>();
            if (nums1.length < nums2.length) {
                int[] tmp = nums1;
                nums1 = nums2;
                nums2 = tmp;
            }

            int len = nums1.length;
            for (int i = 0; i < len; i++) {
                map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
            }

            List<Integer> list = new ArrayList<>();


            for (int i = 0; i < nums2.length; i++) {
                if (map.containsKey(nums2[i])) {
                    list.add(nums2[i]);
                    int val = map.get(nums2[i]) - 1;
                    if (val == 0) map.remove(nums2[i]);
                    else map.put(nums2[i], val);
                }
            }
            return list.stream().mapToInt(Integer::valueOf).toArray();
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        int[] nums1 = new int[]{1,2,2,1};
        int[] nums2 = new int[]{2,2};
        System.out.println(Arrays.toString(s.intersect(nums1, nums2)));
    }


    /* 
        select round(select(distinct(l.user_id) from p) / select)
        from login as l
        where (l.user_id, l.date) in (
            select user_id, DATE_ADD(date,INTERVAL 1 DAY)
            from login
        ) as p
    
    */

}
